'''
Created on 14-Jul-2009

@author: dexen
'''

from dexen.system.common.base import Score, Individual, MAXIMIZE, MINIMIZE

class Fitness(object):
    def __init__(self, inds):
        self.inds = inds

    def _on_pareto_front(self, ind, inds):
        for ind2 in inds:
            if ind2.dominates(ind):
                return False
        return True

    def _extract_pareto_front(self, inds):
        pareto_front = []
        non_pareto_front = []
        
        for ind in inds:
            if self._on_pareto_front(ind, inds):
                pareto_front.append(ind)
            else:
                non_pareto_front.append(ind)
        return pareto_front, non_pareto_front            

    def calc(self):
        fitness = 1
        inds = self.inds
        while len(inds) > 0:
            pareto_front, non_pareto_front = self._extract_pareto_front(inds)
            print "pareto", len(pareto_front), "non pareto", len(non_pareto_front)
            for ind in pareto_front:
                ind.fitness = fitness
            fitness += 1
            inds = non_pareto_front



def main():
    f = open("ind_log.csv", "r")
    content = f.read()
    f.close
    rows = content.split("\r\n")
    score_names = ["daylight", "energy", "privacy"]
    score_types = [MAXIMIZE, MINIMIZE, MAXIMIZE]
    rows = rows[1:-1]
    print len(rows)
    inds = []
    for row in rows:
        values = row.split(",")
        ind = Individual()
        ind.__id__ = int(values[0])
        for i, value in enumerate(values[1:]):
            score = Score(score_names[i], value, score_names[i], score_types[i])
            setattr(ind, score_names[i], score)
        inds.append(ind)
        #print ind.__id__, ind.daylight, ind.energy, ind.privacy
    
    print "I am before fitness"
    fitness = Fitness(inds)
    fitness.calc()
    print "I am after calc"
    
    f = open("ind_log_rank.csv", "w")
    f.write("Id,Daylight,Energy,Privacy\n")
    for ind in inds:
        t = "{0},{1},{2},{3},{4}\n".format(ind.__id__, ind.daylight, ind.energy, ind.privacy, ind.rank)
        f.write(t)
    f.close()
    
    
if __name__ == "__main__":
    main()
